// Himantopus himantopus// insert-videos.js
const { Pool } = require('pg');
const fs = require('fs');
const path = require('path');

// 数据库配置（建议使用环境变量）
const pool = new Pool({
    host: "127.0.0.1",
	user: "postgres",
	password: "whuyiyulu666666",
    //此处是你添加的数据库名
	database: "animalsmigration",
	// multipleStatements: true,
	port : 5432,
});

// 视频文件配置
const videoConfigs = [
  {
    filePath: 'D:/vscode_project/animals_migration/insert_data/data_tobe_inserted/Himantopus himantopus_none2.mp4', // 实际文件路径
    title: 'Himantopus himantopus2',
    animalTags: {
        "animal1": "Himantopus himantopus",
        "animal2": "none"
      }
  },
  // 添加更多视频配置...
];

async function insertVideo(videoConfig) {
    const client = await pool.connect();
    
    try {
      // 读取视频文件
      const videoFile = fs.readFileSync(path.resolve(videoConfig.filePath));
      
      // 生成插入SQL
      const query = `
        INSERT INTO media_files (
          file_name, file_type, mime_type, file_data,
          title, animal_tags
        ) VALUES ($1, $2, $3, $4, $5, $6)
        RETURNING id
      `;
  
      // 构造参数（重点修改部分）
      const values = [
        path.basename(videoConfig.filePath),
        'video',
        'video/mp4',
        videoFile,
        videoConfig.title,
        JSON.stringify(videoConfig.animalTags) // 显式序列化为JSON字符串
      ];
  
      // 执行插入
      const result = await client.query(query, values);
      console.log(`插入成功，ID: ${result.rows[0].id}`);
  
    } catch (error) {
      console.error('插入失败:', error.stack);
    } finally {
      client.release();
    }
  }

// 批量执行插入
async function batchInsert() {
  for (const config of videoConfigs) {
    await insertVideo(config);
  }
  await pool.end();
}

// 启动插入流程
batchInsert()
  .then(() => console.log('全部插入完成'))
  .catch(err => console.error('全局错误:', err));